[CmdletBinding(DefaultParameterSetName="Path")]
param(
    [Parameter(Mandatory=$true, 
               Position=0, 
               ParameterSetName="Path", 
               ValueFromPipeline=$true, 
               ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $Path,

    [Alias("PSPath")]
    [Parameter(Mandatory=$true, 
               Position=0, 
               ParameterSetName="LiteralPath", 
               ValueFromPipelineByPropertyName=$true)]
    [string[]]
    $LiteralPath,

    [Parameter(Position=0,Mandatory=1)]
    [string]$connectionString
)

BEGIN {
    $ErrorActionPreference = "Stop"

    $dbUpAssembly = "$(split-path $MyInvocation.MyCommand.Path)\DbUp.dll"

    if(test-path $dbUpAssembly)
    {
        $dbUpAssemblyPath = get-item $dbUpAssembly
        [System.Reflection.Assembly]::LoadFrom($dbUpAssemblyPath) | out-null
    }
    else {
        throw "Could not find DbUp.dll in the current directory"
        return;
    }

    $sqlFiles = @()
}
PROCESS {
    if ($psCmdlet.ParameterSetName -eq "Path")
    {
        # In the non-literal case we may need to resolve a wildcarded path
        $resolvedPaths = @()
        foreach ($apath in $Path) 
        {
            $resolvedPaths += @(Resolve-Path $apath | Foreach { $_.Path })
        }
    }
    else
    {
        $resolvedPaths = $LiteralPath
    }

    foreach ($rpath in $resolvedPaths) 
    {
        $PathIntrinsics = $ExecutionContext.SessionState.Path
        
        if ($PathIntrinsics.IsProviderQualified($rpath))
        {
            $rpath = $PathIntrinsics.GetUnresolvedProviderPathFromPSPath($rpath)
        }

        Write-Verbose "DbUp Powershell processing $rpath"

        #process file here

        $sqlFiles += [System.IO.FileInfo]$rpath
    }
}
END {
    if($sqlFiles.Count -eq 0){
        write-warning 'No sql scripts executed by DbUp'
    }
    else {
        $scriptProvider = new-object DbUp.ScriptProviders.FileEnumerationScriptProvider -ArgumentList $sqlFiles
        $journal = new-object DbUp.Journal.TableJournal -ArgumentList @($connectionString)
        $scriptExecutor = new-object DbUp.Execution.SqlScriptExecutor -ArgumentList @($connectionString)
        $logger = new-object DbUp.ConsoleLog

        $dbUpgrader = new-object DbUp.DatabaseUpgrader -ArgumentList @($connectionString, $scriptProvider, $journal, $scriptExecutor)
        $dbUpResult = $dbUpgrader.PerformUpgrade($logger)
        if($dbUpResult.Successful){
            write-host -ForegroundColor green "Success!"
        }
        else {
            throw $dbUpResult.Error
        }
    }
}